package com.mikhailenko.transportMVC.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.mikhailenko.transportMVC.model.User;
import com.mikhailenko.transportMVC.service.UserService;
import com.mikhailenko.transportMVC.utils.MD5Util;

@Component
public class UserValidator implements Validator {
	
	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+"
            + "(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+"
            + "(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	private static final String TELEPHONE_PATTERN = "^\\+?[0-9]{3}-?[0-9]{6,12}$";
//	private static final Logger log = Logger.getLogger(UserValidator.class
//			.toString());
	
	
	@Autowired
	private UserService userService;

	@Override
	public boolean supports(Class<?> clazz) {
		return User.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		User user = (User) target;
		String username = user.getUsername();
		String email = user.getEmail();
		String password = user.getPassword();
		String telephone = user.getTelephone();
		User oldUser = null;
		oldUser = userService.findById(user.getUserID());
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "user.username.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "user.password.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fullName", "user.fullName.empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "user.email.empty");
		
		if (username == null || username.length() < 3 ){
			errors.rejectValue("username", "user.username.lessThenTree");
		}
		
		if (email == null || email.matches(EMAIL_PATTERN) == false){
			errors.rejectValue("email", "user.email.invalid");
		}
		
		if (password == null || password.length() < 6 ){
			errors.rejectValue("password", "user.password.invalid");
		}
		
		for (User u: userService.findAll()){
			if (u.getUsername().equals(username) && oldUser == null){
				errors.rejectValue("username", "user.username.alreadyExist");
			}
		}
		
		if (oldUser != null){// in case of user edit
			
			for (User u: userService.findAll()){
				if (u.getUsername().equals(username) && !oldUser.getUsername().equals(username)){
					errors.rejectValue("username", "user.username.alreadyExist");
				}
			}
			
			if (!oldUser.getPassword().equals(MD5Util.encode(password))){
				errors.rejectValue("password", "user.password.wrong");
			}
		}
		
		
		if (!telephone.equals("") ){
			if ( telephone.matches(TELEPHONE_PATTERN) == false){
				errors.rejectValue("telephone", "user.telephone.invalid");
			}
		}
		
	}

}
